import { defineEventHandler, readBody } from "h3";
import { 
  generateVerificationCode, 
  storeVerificationCode, 
  hasVerificationCode,
  getCodeRemainingTime 
} from "../../services/verificationService";
import { emailService } from "../../utils/emailService";

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { email } = body;

    // 数据验证
    if (!email) {
      return {
        success: false,
        error: "邮箱地址不能为空",
      };
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return {
        success: false,
        error: "邮箱格式不正确",
      };
    }

    // 检查是否已有未过期的验证码
    if (hasVerificationCode(email)) {
      const remainingTime = getCodeRemainingTime(email);
      return {
        success: false,
        error: `验证码已发送，请${remainingTime}秒后再试`,
        remainingTime
      };
    }

    // 生成验证码
    const code = generateVerificationCode();
    
    // 存储验证码
    storeVerificationCode(email, code);
    
    // 发送邮件
    const emailResult = await emailService.sendVerificationCode(email, code);
    
    if (!emailResult.success) {
      return {
        success: false,
        error: emailResult.error || "邮件发送失败，请稍后重试",
      };
    }

    return {
      success: true,
      message: "验证码已发送到您的邮箱，请查收",
      // 注意：实际项目中不应该返回验证码给前端
      // 这里仅用于开发测试
      ...(process.env.NODE_ENV === 'development' && { code })
    };
  } catch (error) {
    console.error('发送验证码错误:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "发送验证码失败",
    };
  }
});
